package cn.boodqian.airdata;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.regex.*;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import com.weedong.flex.client.AMFConnection;
import com.weedong.flex.client.ServerStatusException;
import com.weedong.flex.client.ClientStatusException;
import com.weedong.flex.messaging.io.ASObject;
import com.weedong.flex.messaging.util.Base64;

public class ShanghaiUSAirDataProvider implements AirDataProvider {
	private String lasterror = null;
	private String url_fmt = "http://72.166.186.157/feed2js/feed2js.php?src=http://www.beijingaqifeed.com/shanghaiaqi/shanghaiairrss.xml&num=%d";
	
	private final static Logger Log = Logger.getLogger(ShanghaiUSAirDataProvider.class.getName()); 
	
	public ShanghaiUSAirDataProvider() {
	}

	public AirData getAirData(int location, int hours) {
    	ArrayList list = null;
    	ArrayList listpm25 = null;
    	String updateTime = null;
    	
    	assert( hours > 0 );
		if(hours>AirData.MAX_HOURS) hours = AirData.MAX_HOURS;
		
    	ArrayList<Float> hist_pm25_us = new ArrayList<Float>();
    	try {
    		URL url = new URL(String.format(url_fmt, hours));
    		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    		connection.setConnectTimeout(15000);
    		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;

            //title="05-17-2012 18:00; PM2.5; 48.0; 121; Unhealthy for Sensitive Groups (at 24-hour exposure at this level)&hellip;"
            Pattern p = Pattern.compile("title=\"([^\"]+)\"");
            while ((line = reader.readLine()) != null) {
            	Matcher m = p.matcher(line);
            	if(m.find()) {
            		String data = m.group(1);
            		//Log.info("group="+data);
            		String [] array = data.split(";");
            		if(updateTime == null) updateTime = array[0].trim();
            		
            		Float pm25 = 0f;
            		try{	
            			pm25 = Float.parseFloat(array[2].trim());
            		} catch(Exception e) {
            			pm25 = 0f;
            		}
            		hist_pm25_us.add(0, pm25/1000);
            	}
            }
            reader.close();
    	} catch (Exception e) {
    		Log.severe(e.toString());
    		hist_pm25_us.clear();
    		for(int i=0;i<hours;i++) hist_pm25_us.add(0f);
    	}
    	
    	// US data only keeps 45 hours history in max
    	// so we need to padding 0 values ahead
    	// to avoid OutOfBounds exceptions
    	int size = hist_pm25_us.size();
    	for(int i=0;i<hours-size;i++) {
    		hist_pm25_us.add(0, 0f);
    	}
        
    	Date date = new Date();
        try {
        	Pattern p = Pattern.compile("(?ms)(\\d+)-(\\d+)-(\\d+) (\\d+)");
        	Matcher m = p.matcher(updateTime);
        	if (m.find()) {
        		date.setYear(Integer.parseInt(m.group(3))-1900); //Set to current year
        		date.setMonth(Integer.parseInt(m.group(1))-1);
        		date.setDate(Integer.parseInt(m.group(2)));
        		date.setHours(Integer.parseInt(m.group(4)));
        		date.setMinutes(0);
        		date.setSeconds(0);
        	}
		} catch (Exception e) {
			Log.warning("Cannot parse "+updateTime+" to date, using current time\n"+e.toString());
			date.setMinutes(0);
			date.setSeconds(0);
		}
        
        AirData airdata= new AirData();
        airdata.setTime(date);
        airdata.addData("pm25", hist_pm25_us);
    	return airdata;
	}

	public String getLastError() {
		return lasterror;
	}
}
